<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        class="filter-item"
        placeholder="输入关键字进行过滤"
        v-model="filterText"
        style="width: 60%"

      >
      </el-input>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        添加顶级分类
      </el-button>
<!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"-->
<!--                 @click="handleDownload"-->
<!--      >-->
<!--        导出-->
<!--      </el-button>-->
      <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        审核-->
      <!--      </el-checkbox>-->
    </div>
    <div class="block">
      <el-row :gutter="32">
        <el-col :xs="24" :sm="24" :lg="11">
          <el-card>
            <el-divider><font color="#ccc">分类管理</font></el-divider>
      <el-tree
        style="width: 100%"
        :highlight-current="true"
        :data="data"
        node-key="id"
        :expand-on-click-node="false"
        :props="defaultProps"
        ref="tree"
        :filter-node-method="filterNode"
      >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span v-if="data.final>0">  {{ data.label }}
          <font color="#E6A23C">----------《{{data.count}}份文档》<span v-if="data.one_pay == 1">[已开启单篇]</span>
          <span v-else> [未开启单篇]</span>
            </font>
          <font color="#556b2f">
               <el-tooltip class="item" effect="dark" :content="data.special_name" placement="top">
                   <span v-if="data.special_id > 0">
                     [{{data.special_name | ellipsis}}]
                      </span>
               </el-tooltip>
          </font></span>
           <span v-else>{{ data.label }}
             <font color="#556b2f">
              <el-tooltip class="item" effect="dark" :content="data.special_name" placement="top">
                  <span v-if="data.special_id > 0 ">
                     [{{data.special_name | ellipsis}}]
                   </span>
               </el-tooltip>
          </font></span>
        <span>
          <el-button
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            添加
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => edit(data)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            删除
          </el-button>

          <el-switch
            style="margin-left:8px"
            size="mini"
            v-if="data.final>0"
            v-model="data.one_pay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="changeStatus($event,data.id)"
          >
          </el-switch>
        </span>
      </span>
      </el-tree>
           </el-card>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="6">
          <el-card>
            <el-divider><font color="#ccc">已开启单篇付费列表</font></el-divider>
            <el-table v-loading="listLoading" :data="onelist" border fit highlight-current-row style="width: 100%">

              <el-table-column min-width="180px" label="名称">
                <template slot-scope="{row}">
                  <span>{{ row.label }}</span>
                </template>
              </el-table-column>
              <el-table-column class-name="status-col" label="显示状态" width="110">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.show_one"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeShowStatus($event,scope.row.id)"
                  >
                  </el-switch>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="one_total>0" :total="one_total" :page.sync="onepaylist.page" :limit.sync="onepaylist.limit"
                        @pagination="getOnePay"
            />
          </el-card>
        </el-col>.
        <el-col :xs="24" :sm="24" :lg="7">
          <el-card>
            <el-divider><font color="#ccc">排行榜推荐分类(最终分类)</font></el-divider>
            <el-form ref="dataForm" :model="form" label-position="left" label-width="120px"
                     style="width: 80%; margin-left:10%;"
            >
              <el-form-item label="分类一" >
                <el-input v-model="form.one"/>
              </el-form-item>
              <el-form-item label="分类二">
                <el-input v-model="form.two"/>
              </el-form-item>
              <el-form-item label="分类三">
                <el-input v-model="form.three"/>
              </el-form-item>
              <el-form-item label="分类四">
                <el-input v-model="form.four"/>
              </el-form-item>
              <el-form-item label="分类五">
                <el-input v-model="form.five"/>
              </el-form-item>
              <el-divider><font color="#ccc">手机端展示合同列表分类名称</font></el-divider>
              <el-form-item label="列表1" >
                <el-input v-model="form.wap_one"/>
              </el-form-item>
              <el-form-item label="列表2" >
                <el-input v-model="form.wap_two"/>
              </el-form-item>
              <el-form-item label="列表3">
                <el-input v-model="form.wap_three"/>
              </el-form-item>
            </el-form>
              <el-divider>
                <font color="#ccc">
                <el-button type="primary" @click="createForm()">
                  保存
                </el-button>
                </font>
              </el-divider>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
               style="width: 400px; margin-left:50px;"
      >
        <!--        <el-form-item label="Type" prop="type">-->
        <!--          <el-select v-model="temp.type" class="filter-item" placeholder="Please select">-->
        <!--            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="专题">
          <el-select v-model="temp.special_id" filterable placeholder="专题活动"
                     clearable
          >
            <el-option
              v-for="item in specialList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="label">
              <el-input v-model="temp.label"/>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="temp.order"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="temp.status"
            :active-value="1"
            :inactive-value="0"
            active-text="显示"
            inactive-text="隐藏"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():createData()">
            提交
          </el-button>
        </center>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getClass, create, del ,createForm,get_one_pay,changeStatus,changeShowStatus} from '@/api/contract_class'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import clipboard from '@/utils/clipboard'
import store from '@/store'
import router from '@/router'
import { getAll } from '@/api/special'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ContractClass',
  components: { Pagination },
  directives: { waves },
  filters: {
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 12) {
        return value.slice(0, 12) + '...'
      }
      return value
    },
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },

  data() {
    const data = []
    return {
      tableKey: 0,
      list: null,
      onelist:null,
      one_total:0,
      specialList:[],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      onepaylist:{
        page: 1,
        limit: 20,
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      data: JSON.parse(JSON.stringify(data)),
      temp: {
        id: undefined,
        label: '',
        pid: '',
        url: '',
        order: 0,
        status: 0,
        special_id:''
      },
      form: {
        one:'',
        two:'',
        three: '',
        four: '',
        five: '',
        wap_one:'',
        wap_two:'',
        wap_three: '',
      },
      chooseIcon: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        label: [{ required: true, message: '名称不能为空', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getOnePay()
    this.getSpecial()
  },
  methods: {
    getSpecial(){
      getAll().then(response=>{
        this.specialList = response.data
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getOnePay(){
       get_one_pay(this.onepaylist).then(response=>{
          this.onelist = response.data
          this.one_total =response.total
       })
    },
    generateIconCode(symbol) {
      this.chooseIcon = false
      return this.temp.icon = symbol
    },
    changeIcon() {
      this.chooseIcon = true
    },
    generateElementIconCode(symbol) {
      return `<i class="el-icon-${symbol}" />`
    },
    handleClipboard(text, event) {
      clipboard(text, event)
    },
    append(data) {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp.pid = data.id
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      // const newChild = { id: id++, label: 'testtest', children: [] };
      // if (!data.children) {
      //   this.$set(data, 'children', []);
      // }
      // data.children.push(newChild);
    },
    edit(row) {
      this.temp = Object.assign({}, row) // copy obj
      if(this.temp.special_id <= 0){
        this.temp.special_id = ''
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      // const newChild = { id: id++, label: 'testtest', children: [] };
      // if (!data.children) {
      //   this.$set(data, 'children', []);
      // }
      // data.children.push(newChild);
    },

    remove(node, data) {
      this.$confirm('请确认该条数据无子菜单！', '确定要删除该数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(data.id).then(response => {
          // this.list.unshift(this.temp)
          if (response.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
            this.getList()
          } else {
            this.$notify.error({
              title: '失败',
              message: response.msg,
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },

    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
            <span>{node.label}</span>
            <span>
              <el-button size="mini" type="text" on-click={() => this.append(data)}>添加</el-button>
              <el-button size="mini" type="text" on-click={() => this.remove(node, data)}>删除</el-button>
            </span>
          </span>)
    },

    getList() {
      this.listLoading = true
      getClass().then(response => {
        this.data = response.data
        if(response.form){
          this.form = response.form
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    changeStatus(val, id) {
      changeStatus(val, id).then(response => {
        this.$notify.success({
          title: '消息提示',
          message: response.msg,
          offset: 100
        })
        this.getOnePay()
      })
    },
    changeShowStatus(val, id) {
      changeShowStatus(val, id).then(response => {
        this.$notify.success({
          title: '消息提示',
          message: response.msg,
          offset: 100
        })
        this.getOnePay()
      })
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        label: '',
        pid: '',
        url: '',
        order: 0,
        status: 0,
        special_id:''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp.pid = 0
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(response => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            if (response.code == 200) {
              this.$notify.success({
                title: '成功',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.resetTemp()
              this.getList()
              const accessRoutes = store.dispatch('permission/generateRoutes', store.getters.token)
              router.addRoutes(accessRoutes)
            } else {
              this.$notify.error({
                title: '失败',
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    createForm() {
        createForm(this.form).then(response => {
            // this.list.unshift(this.temp)
            if (response.code == 200) {
              this.$notify.success({
                title: '成功',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify.error({
                title: '失败',
                message: response.msg,
                duration: 2000
              })
            }
          })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style>
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #8cbda4;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  padding-bottom: 10px;
}
</style>
<style lang="scss" scoped>
.icons-container {
  margin: 10px 20px 0;

  .grid {
    position: relative;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  }

  .icon-item {
    margin: 20px;
    height: 85px;
    text-align: center;
    width: 100px;
    float: left;
    font-size: 30px;
    color: #24292e;
    cursor: pointer;
  }

  span {
    display: block;
    font-size: 16px;
    margin-top: 10px;
  }

  .disabled {
    pointer-events: none;
  }
}
</style>
<style>
.el-drawer.ltr {
  overflow: scroll;
}
</style>
